//
//  LocationController.swift
//  test-ios
//
//  Created by wyz5204 on 2023/3/19.
//

import UIKit
import CoreLocation
/**
 1 添加定位权限， 在info中
 */
class LocationController: ABaseViewController , CLLocationManagerDelegate {
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("定位成功" ,locations)
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("定位失败" ,error)
    }
    
    
    private lazy var bt : UIButton = {
        return UIButton().then { view in
            view.setTitle("开始定位", for: UIControl.State.normal)
            view.setTitleColor(UIColor.red, for: UIControl.State.normal)
        }
    }()
    
    override func viewDidLoad() {
        
        _locationManager.delegate = self
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest
        _locationManager.distanceFilter = 1.0
        
        bt.addTo(self.view) { [weak self]view in
            
            view.rx.tap.asDriver().drive( onNext : {
                self?.configLocationManager()
            }).disposed(by: self!.rx.disposeBag)
            
            view.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        _locationManager.stopUpdatingLocation()
    }
    
    let _locationManager :CLLocationManager = CLLocationManager.init()
    
    func configLocationManager(){
        print("配置定位 ")
        switch CLLocationManager.authorizationStatus() {
        case .notDetermined:
            print("配置定位 1")
            _locationManager.requestWhenInUseAuthorization()
            break
        case .authorizedWhenInUse, .authorizedAlways:
            print("配置定位 2")
            _locationManager.startUpdatingLocation()
            break
        default:
            break
        }
    }
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        if (manager.authorizationStatus == CLAuthorizationStatus.notDetermined){
            print("等待用户授权")
        }else if(manager.authorizationStatus == CLAuthorizationStatus.authorizedAlways || manager.authorizationStatus == CLAuthorizationStatus.authorizedWhenInUse){
            print("授权成功")
        }else{
            print("授权失败")
        }
    }
}
